package cn.com.cennavi.highTraffic;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

public class MysqlUtils {
	public static Connection getConnection(String url, String username, String password, boolean auto) {
		Connection connection = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection(url, username, password);
			connection.setAutoCommit(auto);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return connection;
	}

	public static boolean closeConnection(Connection connection) {
		boolean isSuccess = true;
		try {
			connection.close();
		} catch (Exception e) {
			e.printStackTrace();
			isSuccess = false;
		}
		return isSuccess;
	}

	/**
	 * 循环遍历路径
	 */
	public static ArrayList<String> quietly(String dir, ArrayList<String> result) {
		// 目录不存在，返回
		File file = new File(dir);
		if (!file.exists()) {
			return result;
		}
		// 遍历路径
		if (file.isDirectory()) {
			File[] filelist = file.listFiles();
			for (File tempdir : filelist) {
				// 递归
				result = quietly(tempdir.toString(), result);
			}
		} else {
			if (file.toString().endsWith(".jar")) {
				result.add(file.toString());
				System.out.println(file.toString());
			}
		}
		return result;
	}

	/**
	 * 循环遍历路径
	 */
	public static ArrayList<String> quietly_hdfs(String dir, ArrayList<String> result) {

		// 遍历目录下的所有文件
		try {
			FileSystem fs = FileSystem.get(new Configuration());
			FileStatus[] status = fs.listStatus(new Path(dir));
			for (FileStatus file : status) {
				if (file.getPath().getName().endsWith(".jar")) {
					System.out.println(file.getPath().toString());
					result.add(file.getPath().toString());
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} 
		return result;
	}

	/**
	 * 解析数据城市码
	 */
	public static String getCityCode(String company) {
		String citycode = "";
		if ("11000005".equals(company)) {
			citycode = "900300";
		} else if ("11000006".equals(company)) {
			citycode = "900300";
		} else if ("10000001".equals(company)) {
			citycode = "900100";
		} else if ("10000005".equals(company)) {
			citycode = "900100";
		} else {
			citycode = company.substring(0, 6);
		}
		return citycode;
	}
}
